<template>
  <ion-page>
    <ion-header :translucent="true">
      <ion-toolbar>
        <ion-buttons slot="start">
          <ion-back-button default-href="/tabs/home"></ion-back-button>
        </ion-buttons>
        <ion-title>发布房源</ion-title>
      </ion-toolbar>
    </ion-header>

    <ion-content :fullscreen="true" class="ion-padding">
      <form @submit.prevent="submitProperty">
        <!-- 基本信息 -->
        <div class="form-section">
          <h3>基本信息</h3>
          
          <ion-item>
            <ion-label position="stacked">房源标题 *</ion-label>
            <ion-input 
              v-model="propertyForm.title" 
              placeholder="请输入房源标题"
              required
            ></ion-input>
          </ion-item>

          <ion-item>
            <ion-label position="stacked">房源地址 *</ion-label>
            <ion-input 
              v-model="propertyForm.address" 
              placeholder="请输入详细地址"
              required
            ></ion-input>
          </ion-item>

          <ion-item>
            <ion-label position="stacked">房源类型 *</ion-label>
            <ion-select v-model="propertyForm.type" placeholder="请选择房源类型">
              <ion-select-option value="apartment">公寓</ion-select-option>
              <ion-select-option value="house">别墅</ion-select-option>
              <ion-select-option value="studio">单间</ion-select-option>
              <ion-select-option value="shared">合租</ion-select-option>
            </ion-select>
          </ion-item>

          <div class="row-inputs">
            <ion-item>
              <ion-label position="stacked">面积 (㎡) *</ion-label>
              <ion-input 
                v-model="propertyForm.area" 
                type="number" 
                placeholder="0"
                required
              ></ion-input>
            </ion-item>

            <ion-item>
              <ion-label position="stacked">楼层</ion-label>
              <ion-input 
                v-model="propertyForm.floor" 
                type="number" 
                placeholder="1"
              ></ion-input>
            </ion-item>
          </div>

          <div class="row-inputs">
            <ion-item>
              <ion-label position="stacked">房间数</ion-label>
              <ion-input 
                v-model="propertyForm.rooms" 
                type="number" 
                placeholder="1"
              ></ion-input>
            </ion-item>

            <ion-item>
              <ion-label position="stacked">卫生间数</ion-label>
              <ion-input 
                v-model="propertyForm.bathrooms" 
                type="number" 
                placeholder="1"
              ></ion-input>
            </ion-item>
          </div>
        </div>

        <!-- 租金信息 -->
        <div class="form-section">
          <h3>租金信息</h3>
          
          <ion-item>
            <ion-label position="stacked">月租金 (元) *</ion-label>
            <ion-input 
              v-model="propertyForm.price" 
              type="number" 
              placeholder="0"
              required
            ></ion-input>
          </ion-item>

          <ion-item>
            <ion-label position="stacked">押金 (元)</ion-label>
            <ion-input 
              v-model="propertyForm.deposit" 
              type="number" 
              placeholder="0"
            ></ion-input>
          </ion-item>

          <ion-item>
            <ion-label position="stacked">付款方式</ion-label>
            <ion-select v-model="propertyForm.paymentMethod" placeholder="请选择付款方式">
              <ion-select-option value="monthly">月付</ion-select-option>
              <ion-select-option value="quarterly">季付</ion-select-option>
              <ion-select-option value="semi-annual">半年付</ion-select-option>
              <ion-select-option value="annual">年付</ion-select-option>
            </ion-select>
          </ion-item>
        </div>

        <!-- 房源描述 -->
        <div class="form-section">
          <h3>房源描述</h3>
          
          <ion-item>
            <ion-label position="stacked">详细描述</ion-label>
            <ion-textarea
              v-model="propertyForm.description"
              placeholder="请描述房源的特色、周边环境、交通情况等..."
              :rows="4"
            ></ion-textarea>
          </ion-item>

          <ion-item>
            <ion-label position="stacked">配套设施</ion-label>
            <div class="facilities-grid">
              <ion-chip 
                v-for="facility in availableFacilities" 
                :key="facility.value"
                :color="propertyForm.facilities.includes(facility.value) ? 'primary' : 'medium'"
                @click="toggleFacility(facility.value)"
              >
                <ion-icon :icon="facility.icon"></ion-icon>
                <ion-label>{{ facility.label }}</ion-label>
              </ion-chip>
            </div>
          </ion-item>
        </div>

        <!-- 联系信息 -->
        <div class="form-section">
          <h3>联系信息</h3>
          
          <ion-item>
            <ion-label position="stacked">联系人 *</ion-label>
            <ion-input 
              v-model="propertyForm.contactName" 
              placeholder="请输入联系人姓名"
              required
            ></ion-input>
          </ion-item>

          <ion-item>
            <ion-label position="stacked">联系电话 *</ion-label>
            <ion-input 
              v-model="propertyForm.contactPhone" 
              type="tel" 
              placeholder="请输入联系电话"
              required
            ></ion-input>
          </ion-item>
        </div>

        <!-- 提交按钮 -->
        <div class="submit-section">
          <ion-button 
            expand="block" 
            type="submit" 
            :disabled="!isFormValid"
            class="submit-btn"
          >
            发布房源
          </ion-button>
        </div>
      </form>
    </ion-content>
  </ion-page>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { usePropertyStore } from '@/stores/property'
import { useUserStore } from '@/stores/user'
import {
  IonPage,
  IonHeader,
  IonToolbar,
  IonTitle,
  IonContent,
  IonButtons,
  IonBackButton,
  IonItem,
  IonLabel,
  IonInput,
  IonTextarea,
  IonSelect,
  IonSelectOption,
  IonButton,
  IonChip,
  IonIcon,
  toastController,
  alertController
} from '@ionic/vue'
import {
  wifiOutline,
  tvOutline,
  carOutline,
  snowOutline,
  bedOutline,
  restaurantOutline,
  waterOutline,
  flashOutline
} from 'ionicons/icons'

const router = useRouter()
const propertyStore = usePropertyStore()
const userStore = useUserStore()

// 房源表单数据
const propertyForm = ref({
  title: '',
  address: '',
  type: '',
  area: null,
  floor: null,
  rooms: 1,
  bathrooms: 1,
  price: null,
  deposit: null,
  paymentMethod: '',
  description: '',
  facilities: [] as string[],
  contactName: '',
  contactPhone: ''
})

// 可选设施
const availableFacilities = [
  { value: 'wifi', label: 'WiFi', icon: wifiOutline },
  { value: 'tv', label: '电视', icon: tvOutline },
  { value: 'parking', label: '停车位', icon: carOutline },
  { value: 'ac', label: '空调', icon: snowOutline },
  { value: 'furniture', label: '家具', icon: bedOutline },
  { value: 'kitchen', label: '厨房', icon: restaurantOutline },
  { value: 'washing', label: '洗衣机', icon: waterOutline },
  { value: 'heating', label: '暖气', icon: flashOutline }
]

// 切换设施选择
const toggleFacility = (facility: string) => {
  const index = propertyForm.value.facilities.indexOf(facility)
  if (index > -1) {
    propertyForm.value.facilities.splice(index, 1)
  } else {
    propertyForm.value.facilities.push(facility)
  }
}

// 表单验证
const isFormValid = computed(() => {
  return propertyForm.value.title &&
         propertyForm.value.address &&
         propertyForm.value.type &&
         propertyForm.value.area &&
         propertyForm.value.price &&
         propertyForm.value.contactName &&
         propertyForm.value.contactPhone
})

// 提交房源
const submitProperty = async () => {
  if (!isFormValid.value) {
    const toast = await toastController.create({
      message: '请填写所有必填项',
      duration: 2000,
      color: 'warning',
      position: 'top'
    })
    await toast.present()
    return
  }

  const alert = await alertController.create({
    header: '确认发布',
    message: '确定要发布这个房源吗？',
    buttons: [
      {
        text: '取消',
        role: 'cancel'
      },
      {
        text: '确定发布',
        handler: async () => {
          try {
            // 保存房源到存储
            const newProperty = propertyStore.addProperty(
              propertyForm.value,
              userStore.user?.id?.toString() || 'unknown'
            )

            console.log('发布房源成功:', newProperty)

            const toast = await toastController.create({
              message: '房源发布成功！',
              duration: 2000,
              color: 'success',
              position: 'top'
            })
            await toast.present()

            // 返回首页
            router.replace('/tabs/home')
          } catch (error) {
            console.error('发布房源失败:', error)
            const toast = await toastController.create({
              message: '发布房源失败，请重试',
              duration: 2000,
              color: 'danger',
              position: 'top'
            })
            await toast.present()
          }
        }
      }
    ]
  })
  await alert.present()
}
</script>

<style scoped>
.form-section {
  margin-bottom: 24px;
}

.form-section h3 {
  margin: 0 0 16px 0;
  color: var(--ion-color-dark);
  font-weight: 600;
  font-size: 18px;
}

.row-inputs {
  display: flex;
  gap: 12px;
}

.row-inputs ion-item {
  flex: 1;
}

.facilities-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  padding: 12px 0;
}

.facilities-grid ion-chip {
  cursor: pointer;
  transition: all 0.2s ease;
}

.submit-section {
  margin-top: 32px;
  padding-bottom: 20px;
}

.submit-btn {
  --border-radius: 12px;
  height: 48px;
  font-weight: 600;
}

ion-item {
  --border-radius: 8px;
  --background: white;
  margin-bottom: 12px;
}

ion-input, ion-textarea, ion-select {
  --padding-start: 12px;
}
</style>
